package com.happy.config;

import com.happy.util.StateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle ( HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception {
        if ( HttpMethod.OPTIONS.toString ().equals ( request.getMethod () ) ) {
            response.setStatus ( HttpServletResponse.SC_OK );
            return true;
        }
        String token = request.getHeader ( "Token" );
//        if ( token == null || "".equals ( token ) ) {
//            response.setHeader ( "Content-type", "application/json;charset=UTF-8" );
//            response.setCharacterEncoding ( "UTF-8" );
//            PrintWriter out = response.getWriter ();
//            out.write ( StateEnum.REQUEST_POWER_EXCE.getCode () );
//            return false;
//        }
        String userToken = (String) request.getSession ().getAttribute ( "token" );
        // 暂未使用session用户，如若需要则要改成redis或者其他session共享组件，shiro
//        if ( userToken == null ) {
//            response.setHeader ( "Content-type", "application/json;charset=UTF-8" );
//            response.setCharacterEncoding ( "UTF-8" );
//            PrintWriter out = response.getWriter ();
//            out.write ( StateEnum.REQUEST_POWER_EXCE.getCode () );
//            return false;
//        }
        return true;
    }

    @Override
    public void postHandle ( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView ) throws Exception {

    }

    @Override
    public void afterCompletion ( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex ) throws Exception {

    }
}
